package com.example.homework.controller;

import com.example.homework.entity.Student;
import com.example.homework.entity.vo.StudentVo;
import com.example.homework.service.studentService;
import com.example.homework.util.R;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
public class studentController {
    @Resource
    private studentService studentService;

    @PutMapping("insert/{id}")
    public R addStudent(@RequestBody StudentVo student, @PathVariable String id) {
        //String hobby = null;
        Integer studentId = null;
        String[] hobby1 = student.getHobby();
        String hobby = String.join(" ", hobby1);

        if (!id.equals("null")) {
            //System.out.println(id);
            studentId = Integer.parseInt(id);
        }

        Student student1 = new Student(studentId, student.getAccount(), student.getPassword(), student.getSex(), hobby, student.getAddress(), student.getInfo());
        boolean result = studentService.saveOrUpdate(student1);
        if (result) {
            return R.success("成功");
        } else
            return R.success("失败");
    }

    @GetMapping("get")
    public R getStudent() {
        List<Student> list = studentService.list();
        if (list.isEmpty()) {
            return R.success("空");
        } else
            return R.success("成功", list);
    }

    @GetMapping("delete")
    public R deleteStudent(Integer id) {
        boolean remove = studentService.removeById(id);
        R student = getStudent();
        if (remove) {
            return R.success("成功", student.getData());
        } else
            return R.success("失败");

    }

    @GetMapping("getOne")
    public R queryById(Integer id) {
        System.out.println("id = " + id);
        Student student = studentService.getById(id);
        String hobby = student.getHobby();
        String[] hobbies = hobby.split(" ");
        //System.out.println(student);

        StudentVo studentVo = new StudentVo(student.getAccount(), student.getPassword(), student.getSex(), hobbies, student.getAddress(), student.getInfo());
        System.out.println("studentVo = " + studentVo);
        return R.success("成功", studentVo);
    }


}
